package com.tjian.fafa.user.base.chatServices;


import com.tjian.fafa.user.base.bean.UserInfo;
import com.tjian.fafa.user.base.util.UnsavedChatMsg;
import com.tjian.util.TypeUtil;

import java.util.ArrayList;
import java.util.List;


public class InitData extends Thread
{

    /* singleton instance */
    private static InitData initData;

    private UserInfo userInfo;
    private boolean msg3Recev;

    private List<UserInfo> mListOfFriends;
    private boolean msg5Recev;

    public static InitData getInitData()
    {
        if (initData == null)
        {
            initData = new InitData();
        }
        return initData;
    }

    private InitData()
    {
        msg3Recev = false;
        msg5Recev = false;
        mListOfFriends = new ArrayList<UserInfo>();
    }

    @Override
    public void run()
    {
        //循环终止条件写true，这种情况，是需要在循环内主动终止循环的，要么使用return返回，要么使用break跳出循环。用在哪里呢？
        // 比如socket连接，服务端就需要一直等到客户端输入啊响应啊这么样的。
        while (!(msg3Recev && msg5Recev)) ;

        //System.out.println("==========,_20161119_120308,\n" + TypeUtil.typeToString("flag", flag));


    }

    public void msgHandShakeArrive(String str)
    {
        userInfo = new UserInfo(str);
        msg3Recev = true;
        if (userInfo.getId() < 0)    // invalid username or password, no friendlist will be sent
        {
            msg5Recev = true;
        }
    }

    public void msg5Arrive(String str)
    {
        String strSplitter = FriendListInfo.strSplitter;
        String[] strArr0 = str.split(strSplitter);
        int count = Integer.parseInt(strArr0[0]);
        ChatServiceData mChatServiceData = ChatServiceData.getInstance();
        /*haoren2  count=2,str=2!!!!!&&&!haoren&#&1&#&1&#&1&#&0&#&1991&#&9&#&9&#&xx&#&xx&#&xx&#&imgs/avatar/2014/12/27/haoren.jpg&#&!!!!!&&&!haoren1&#&2&#&0&#&0&#&1&#&1991&#&1&#&1&#&xx&#&xx&#&xx&#&imgs/avatar/2014/12/27/haoren1.jpg&#&!!!!!&&&!*/
        for (int p = 1; p <= count; p++)
        {
            UserInfo userInfo = new UserInfo(strArr0[p]);
            mListOfFriends.add(userInfo);
            mChatServiceData.newUser(userInfo);
            UnsavedChatMsg.getInstance().newUser(userInfo);
        }
        msg5Recev = true;
    }

    public UserInfo getUserInfo()
    {
        return userInfo;
    }

    public List<UserInfo> getListOfFriends()
    {
        return mListOfFriends;
    }

    // to close initData in order to avoid same thread being started twice
    public static void closeInitData()
    {
        initData = null;
    }
}
